const Base = require('./base.js');
const API = require('co-wechat-api');
const fs = require('fs');
module.exports = class extends Base {
	constructor(ctx) {
		super(ctx);

		this.msg = this.model("weixin/msg");
		this.conf = this.model("weixin/config");
		this.txt = this.model("weixin/txt");
		this.news = this.model("weixin/news");
		this.msg_reply = this.model("weixin/msg_reply");
	

	}
	async indexAction() {
		if(this.isGet) {
			let gets = this.get();
			let wxid = gets.id;
			let wxlist = await this.conf.select();
			if(!wxid && wxlist && wxlist.length > 0) {
				wxid = wxlist[0].id;
			}
			this.assign("wxid", wxid);
			this.assign("wxlist", wxlist);
			return this.display();
		}
		if(this.isPost) {
			let posts = this.post();
			let where = {};

			if(!think.isEmpty(posts.wxid)) {
				where.wxid = posts.wxid;
			}

			if(!think.isEmpty(posts.nickname)) {
				where.nickname = ['like', '%' + posts.nickname + '%'];
			}

			if(!think.isEmpty(posts.content)) {
				where.content = ['like', '%' + posts.content + '%'];
			}

			const data = await this.msg.dataTable(posts, where);
			console.log(JSON.stringify(data))
			return this.json(data);
		}

	}

	async replyAction() {
		try {
			if(this.isGet) {
				let gets = this.get();

				let msg = await this.msg.findOne(gets.id);
				this.assign("type", gets.type || 0);
				this.assign("msg", msg || {});
				return this.display();
			}
			if(this.isPost) {

				let posts = this.post();
				let user = await this.session("user");
				let api = await this.wechatApi(posts.wxid);
				let res = await api.sendText(posts.openid, posts.content);
				console.log(res);
				console.log("383883838383833838")
				if(res.errcode == 0) {
					let replyid = await this.msg_reply.add({
						msg_id: posts.id,
						user_id: posts.user_id,
						openid: posts.openid,
						type: 'text',
						content: posts.content,
						create_by: user.id,
						create_time: new Date().valueOf(),
						wxid: posts.wxid
					});
					if(!think.isEmpty(replyid)) {
						await this.msg.setOne(posts.id, {
							reply_id: replyid
						});
					}
					return this.success("发送成功");

				} else {
					return this.fail("发送失败");
				}

			}
		} catch(e) {
			console.log(e)
		}
	}
	async replyListAction() {
		try {

			let gets = this.get();
			let where = {};
			if(!think.isEmpty(gets.openid)) {
				where.openid = gets.openid;
			}

			let msgs = await this.msg.where(where).order({
				create_time: 'DESC'
			}).page(gets.pageNum, gets.pageSize || 5).countSelect();
			console.log(msgs)
			return this.json(msgs);
		} catch(e) {
			console.log(e)
		}
	}

};